package ysq.xyg.base.exception;

import org.apache.shiro.authz.AuthorizationException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.validation.BindException;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.HttpRequestMethodNotSupportedException;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.MissingServletRequestParameterException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import ysq.xyg.base.model.dto.ReturnEntity;
import ysq.xyg.base.util.BaseConstant;

import javax.validation.ConstraintViolation;
import javax.validation.ConstraintViolationException;
import java.util.Set;

/**
 * 自定义异常处理器
 *
 * @author ruoyi
 */
@ControllerAdvice
public class DefaultExceptionHandler {

    private static final Logger log = LoggerFactory.getLogger(DefaultExceptionHandler.class);

    /**
     * 权限校验失败
     */
    @ResponseBody
    @ExceptionHandler(AuthorizationException.class)
    public ReturnEntity handleAuthorizationException(AuthorizationException e) {
        log.error(e.getMessage(), e);
        return new ReturnEntity(BaseConstant.FAIL, "您没有数据的权限，请联系管理员添加");
    }

    /**
     * 请求方式不支持
     */
    @ResponseBody
    @ExceptionHandler({ HttpRequestMethodNotSupportedException.class })
    public ReturnEntity handleException(HttpRequestMethodNotSupportedException e) {
        log.error(e.getMessage(), e);
        return new ReturnEntity(BaseConstant.FAIL, "不支持' " + e.getMethod() + "'请求");
    }

    /**
     * 拦截未知的运行时异常
     */
    @ResponseBody
    @ExceptionHandler(RuntimeException.class)
    public ReturnEntity notFount(RuntimeException e) {
        log.error("运行时异常:", e);
        return new ReturnEntity(BaseConstant.FAIL, "运行时异常:" + e.getMessage());
    }

    /**
     * 自定义异常
     */
    @ResponseBody
    @ExceptionHandler(UCException.class)
    public ReturnEntity handleUCException(UCException e){
        return new ReturnEntity(BaseConstant.FAIL, e.getMessage());
    }

    /**
     * 系统异常
     */
    @ResponseBody
    @ExceptionHandler(Exception.class)
    public ReturnEntity handleException(Exception e) {
        log.error(e.getMessage(), e);
        return new ReturnEntity(BaseConstant.FAIL, "服务器错误，请联系管理员");
    }

    /**
     * 方法参数校验
     */
    @ResponseBody
    @ExceptionHandler(MissingServletRequestParameterException.class)
    public ReturnEntity handleMissingServletRequestParameterException(MissingServletRequestParameterException e) {
        log.error(e.getMessage(), e);
        return new ReturnEntity(BaseConstant.FAIL, e.getMessage());
    }

    /**
     * 数据校验异常
     */
    @ResponseBody
    @ExceptionHandler(BindException.class)
    public ReturnEntity handleBindException(BindException e) {
        BindingResult bindingResult = e.getBindingResult();
        // getFieldError():随机返回一个对象属性的异常信息。如果要一次性返回所有对象属性异常信息，则调用ex.getAllErrors()
        FieldError fieldError = bindingResult.getFieldError();
        return new ReturnEntity(BaseConstant.FAIL, fieldError.getDefaultMessage());
    }

    /**
     * 数据校验异常
     */
    @ResponseBody
    @ExceptionHandler(ConstraintViolationException.class)
    public ReturnEntity handleBindException(ConstraintViolationException e) {
        Set<ConstraintViolation<?>> constraintViolations = e.getConstraintViolations();
        StringBuilder sb = new StringBuilder();
        for (ConstraintViolation<?> violation : constraintViolations) {
            sb.append(violation.getMessage());
        }
        return new ReturnEntity(BaseConstant.FAIL, sb.toString());
    }

    /**
     * 数据校验异常
     */
    @ResponseBody
    @ExceptionHandler(MethodArgumentNotValidException.class)
    public ReturnEntity handleBindException(MethodArgumentNotValidException e) {
        // ex.getFieldError():随机返回一个对象属性的异常信息。如果要一次性返回所有对象属性异常信息，则调用ex.getAllErrors()
        BindingResult bindingResult = e.getBindingResult();
        FieldError fieldError = bindingResult.getFieldError();
        /*StringBuilder sb = new StringBuilder();
        sb.append(fieldError.getField())
                .append("=[")
                .append(fieldError.getRejectedValue())
                .append("]")
                .append(fieldError.getDefaultMessage());*/
        return new ReturnEntity(BaseConstant.FAIL, fieldError.getDefaultMessage());
    }

}
